/*
 * @Author: Ceoifung
 * @Date: 2023-04-17 09:58:23
 * @LastEditors: Ceoifung
 * @LastEditTime: 2023-04-17 10:32:14
 * @Description: XiaoRGEEK All Rights Reserved. Copyright © 2023
 */
#include "xr_main.h"

TCPServer tcp;

typedef Json::Writer JsonWriter;
typedef Json::Reader JsonReader;
typedef Json::Value JsonValue;

/**
 * @brief 退出TCP监听，结束TCP服务
 *
 * @param s
 */
void close_app(int s)
{
    tcp.closed();
    exit(0);
}

/**
 * @brief 打印遍历所有的json数据
 *
 * @param data
 */
void print_json(JsonValue data)
{
    JsonValue::Members mem = data.getMemberNames();
    printf("----------------------------------------------\n");
    for (auto iter = mem.begin(); iter != mem.end(); iter++)
    {
        cout << *iter << "\t: ";
        if (data[*iter].type() == Json::objectValue)
        {
            cout << endl;
            print_json(data[*iter]);
        }
        else if (data[*iter].type() == Json::arrayValue)
        {
            cout << endl;
            auto cnt = data[*iter].size();
            for (auto i = 0; i < cnt; i++)
            {
                print_json(data[*iter][i]);
            }
        }
        else if (data[*iter].type() == Json::stringValue)
        {
            cout << data[*iter].asString() << endl;
        }
        else if (data[*iter].type() == Json::realValue)
        {
            cout << data[*iter].asDouble() << endl;
        }
        else if (data[*iter].type() == Json::uintValue)
        {
            cout << data[*iter].asUInt() << endl;
        }
        else
        {
            cout << data[*iter].asInt() << endl;
        }
    }
    printf("----------------------------------------------\n");
    return;
}

/**
 * @brief 发送数据
 *
 * @param value JsonValue
 * @param id 客户端ID
 */
void send_data(JsonValue value, int id)
{
    JsonValue root;
    root["type"] = "echo";
    root["data"] = value;
    tcp.Send(Json::FastWriter().write(root), id);
}

/**
 * @brief 解析收到的数据
 *
 * @param buffer 数据
 */
void decode_data(string buffer, int id)
{
    JsonReader reader;
    JsonValue values;

    if (reader.parse(buffer, values))
    {
        // cout << "receive"
        printf("received data:\n");
        print_json(values);
        send_data(values, id);
        if (values["type"] == "power")
        {
            // printf("power\n");
        }
    }
    else
        cerr << "数据解析错误" << endl;
    // free(values);
}

/**
 * @brief 接收函数
 *
 * @param m
 * @return void*
 */
void *recv_message(void *m)
{
    pthread_detach(pthread_self());
    vector<descript_socket *> desc;
    while (1)
    {
        desc = tcp.getMessage();
        if (!desc.empty())
        {
            for (unsigned int i = 0; i < desc.size(); i++)
            {
                if (!desc[i]->enable_message_runtime)
                {
                    desc[i]->enable_message_runtime = true;
                }
                decode_data(desc[i]->message, i);
                // tcp.Send(desc[i]->message, i);
                tcp.clean(i);
            }
        }
    }
}

int main(int argc, char **argv)
{
    std::signal(SIGINT, close_app);
    pthread_t *msg = (pthread_t *)malloc(1 * sizeof(pthread_t));
    vector<int> opts = {SO_REUSEPORT, SO_REUSEADDR};
    if (tcp.setup(2001, opts) == 0)
    {
        
        if (pthread_create(&msg[0], NULL, recv_message, (void *)0) == 0)
        {
            while (1)
            {
                tcp.accepted();
            }
        }
    }
    else
    {
        cerr << "Error apertura socket" << endl;
    }
    free(msg);
    msg = NULL;
    return 0;
}